<template>
  <div class="process-container">
    <!-- 顶部操作栏 -->
    <div class="top-bar">
      <a-space size="large">
        <a-button size="large" @click="goBack">
          <template #icon><IconArrowLeft /></template>
          返回
        </a-button>
        <a-button
          type="primary"
          size="large"
          :loading="approveLoading"
          @click="showApproveModal"
          v-perm="['lindi:tradeApplication:process']"
        >
          <template #icon><IconCheckCircle /></template>
          立即审批
        </a-button>
      </a-space>
    </div>

    <div class="process-content">
      <!-- 基础信息 -->
       <BasicInfoView :data="basicInfo" :loading="loading" class="mb-4" />

      <!-- 详细信息标签页 -->
      <a-card title="详细信息" class="mb-4">
        <a-tabs v-model:active-key="activeTab" type="line" size="large">
          <a-tab-pane key="quota" title="指标调配" v-perm="['lindi:indexChangeRecord:get']">
            <QuotaAllocationRecord
              :trade-application-id="tradeApplicationId"
              :loading="loading"
            />
          </a-tab-pane>

          <a-tab-pane key="confirmation" title="确认函管理" v-perm="['lindi:tradeApplicationConfirmLetter:get']">
            <ConfirmationLetterManagement
              :trade-application-id="tradeApplicationId"
              :loading="loading"
            />
          </a-tab-pane>

          <a-tab-pane key="contract" title="合同管理" v-perm="['lindi:tradeApplicationContract:get']">
            <ContractManagement
              :trade-application-id="tradeApplicationId"
              :loading="loading"
            />
          </a-tab-pane>

          <a-tab-pane key="invoice" title="发票管理" v-perm="['lindi:tradeApplicationInvoice:get']">
            <InvoiceManagement
              :trade-application-id="tradeApplicationId"
              :loading="loading"
            />
          </a-tab-pane>

          <a-tab-pane key="payment" title="付款凭证" v-perm="['lindi:tradeApplicationCredit:get']">
            <PaymentVoucherManagement
              :trade-application-id="tradeApplicationId"
              :loading="loading"
            />
          </a-tab-pane>

          <a-tab-pane key="attachment" title="审批文件" v-perm="['lindi:tradeApplicationApproveFile:get']">
            <RelatedAttachments
              :trade-application-id="tradeApplicationId"
              :loading="loading"
            />
          </a-tab-pane>

          <a-tab-pane v-if="false" key="history" title="审批历史" v-perm="['lindi:tradeApplicationOperator:get']">
            <ApprovalHistory
              :trade-application-id="tradeApplicationId"
              :loading="loading"
            />
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>

    <!-- 改进的审批弹窗 -->
    <a-modal
      v-model:visible="approveModalVisible"
      title="审批操作"
      width="700px"
      :footer="false"
      @cancel="resetApproveForm"
    >
      <div class="approve-modal-content">
        <a-form
          ref="approveFormRef"
          :model="approveForm"
          :rules="approveRules"
          layout="vertical"
        >
          <a-form-item field="approvalResult" label="审批结果" required>
            <a-radio-group v-model="approveForm.approvalResult" size="large">
              <a-radio value="approved">
                <template #radio="{ checked }">
                  <a-space>
                    <IconCheckCircle
                      :style="{ color: checked ? '#00b42a' : '' }"
                    />
                    <span>通过</span>
                  </a-space>
                </template>
              </a-radio>
              <a-radio value="rejected">
                <template #radio="{ checked }">
                  <a-space>
                    <IconCloseCircle
                      :style="{ color: checked ? '#f53f3f' : '' }"
                    />
                    <span>驳回</span>
                  </a-space>
                </template>
              </a-radio>
            </a-radio-group>
          </a-form-item>

          <!-- 只有驳回时才显示审批意见 -->
          <a-form-item
            v-if="approveForm.approvalResult === 'rejected'"
            field="approvalComment"
            label="审批意见"
            required
          >
            <a-textarea
              v-model="approveForm.approvalComment"
              :auto-size="{ minRows: 4, maxRows: 8 }"
              placeholder="请详细说明驳回理由..."
              show-word-limit
              :max-length="500"
            />
          </a-form-item>



          <!-- 交易编号设置 (仅当交易状态为2且审批结果为通过时显示) -->
          <div
            v-if="
              approveForm.approvalResult === 'approved' &&
              basicInfo.tradeStatus === 2
            "
            class="trade-code-section"
          >
            <a-divider>交易编号设置</a-divider>

            <!-- 交易编号生成方式选择 -->
            <a-form-item field="tradeCodeType" label="交易编号生成方式">
              <a-radio-group v-model="approveForm.tradeCodeType" size="large">
                <a-radio value="auto">
                  <template #radio="{ checked }">
                    <a-space>
                      <icon-robot
                        :style="{ color: checked ? '#165dff' : '' }"
                      />
                      <span>自动生成</span>
                    </a-space>
                  </template>
                </a-radio>
                <a-radio value="manual">
                  <template #radio="{ checked }">
                    <a-space>
                      <icon-edit :style="{ color: checked ? '#165dff' : '' }" />
                      <span>手动输入</span>
                    </a-space>
                  </template>
                </a-radio>
              </a-radio-group>
            </a-form-item>

            <!-- 手动输入交易编号 -->
            <a-form-item
              v-if="approveForm.tradeCodeType === 'manual'"
              field="tradeCode"
              label="交易编号"
              required
            >
              <a-input
                v-model="approveForm.tradeCode"
                placeholder="请输入交易编号"
                size="large"
                :max-length="50"
                show-word-limit
              />
              <template #help>
                <div class="text-gray-500 text-sm mt-1">
                  建议格式：JY + 年月日 + 序号，如：JY20241201001
                </div>
              </template>
            </a-form-item>

            <!-- 自动生成说明 -->
            <div
              v-if="approveForm.tradeCodeType === 'auto'"
              class="auto-generate-info"
            >
              <a-alert type="info" show-icon>
                <template #icon><icon-info-circle /></template>
                系统将自动生成交易编号，格式为：JY + 年月日 + 6位随机数
              </a-alert>
            </div>
          </div>



          <!-- 审批操作按钮 -->
          <div class="approve-actions">
            <a-space size="large">
              <a-button size="large" @click="resetApproveForm">取消</a-button>
              <a-button
                type="primary"
                size="large"
                :loading="approveLoading"
                @click="handleApprove"
                :disabled="
                  !approveForm.approvalResult ||
                  (approveForm.approvalResult === 'rejected' &&
                    !approveForm.approvalComment)
                "
              >
                确认审批
              </a-button>
            </a-space>
          </div>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import {
  defineProps,
  defineEmits,
  getCurrentInstance,
  onMounted,
  reactive,
  ref,
  watch,
  computed,
} from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import {
  IconArrowLeft,
  IconCheckCircle,
  IconCloseCircle,
  IconDown,
  IconFile,
  IconFilePdf,
  IconEye,
  IconDownload,
  IconRobot,
  IconEdit,
  IconInfoCircle,
} from "@arco-design/web-vue/es/icon";
import {
  getTradeApplicationByTradeApplicationIdApi,
  approveTradeApplicationApi,
} from "~/api/lindi/tradeApplication";

import { DICT } from "~/utils/dict.js";
import { hasPerm } from "~/utils/sys.js";

// 导入子组件
import BasicInfoView from "./components/BasicInfoView.vue";
import QuotaAllocationRecord from "./components/QuotaAllocationRecord.vue";
import ContractManagement from "./components/ContractManagement.vue";
import InvoiceManagement from "./components/InvoiceManagement.vue";
import PaymentVoucherManagement from "./components/PaymentVoucherManagement.vue";
import ConfirmationLetterManagement from "./components/ConfirmationLetterManagement.vue";
import RelatedAttachments from "./components/RelatedAttachments.vue";
import ApprovalHistory from "./components/ApprovalHistory.vue";

// 定义props
const props = defineProps({
  tradeApplicationId: {
    type: String,
    required: true,
  },
});

// 定义事件
const emit = defineEmits(["cancel", "approved"]);

// 全局实例
const { proxy } = getCurrentInstance();

// 加载字典
const dicts = proxy.LoadDicts([
  DICT.lindiTradeStatus,
]);

// 响应式数据
const loading = ref(false);
const approveLoading = ref(false);
const approveModalVisible = ref(false);
const approveFormRef = ref(null);
const activeTab = ref("quota");
const infoExpanded = ref(false);

const activeKeys = ref([]);

// 基础信息数据
const basicInfo = ref({});

// 附件数据
const attachmentData = ref({
  redlineFiles: [],
  attachmentFiles: [],
});

// 审批表单
const approveForm = reactive({
  approvalResult: "",
  approvalComment: "",
  tradeCodeType: "auto", // 交易编号生成方式：auto-自动生成，manual-手动输入
  tradeCode: "", // 手动输入的交易编号
});



// 审批表单规则
const approveRules = {
  approvalResult: [{ required: true, message: "请选择审批结果" }],
  approvalComment: [
    { required: true, message: "请输入审批意见" },
    { minLength: 5, message: "审批意见至少5个字符" },
  ],
  tradeCode: [
    { required: true, message: "请输入交易编号", trigger: "blur" },
    { minLength: 5, message: "交易编号至少5个字符", trigger: "blur" },
    { maxLength: 50, message: "交易编号不能超过50个字符", trigger: "blur" },
    {
      pattern: /^[A-Z0-9]+$/,
      message: "交易编号只能包含大写字母和数字",
      trigger: "blur",
    },
  ],
};

// 返回列表页
const goBack = () => {
  emit("cancel");
};

// 显示审批弹窗
const showApproveModal = () => {
  approveModalVisible.value = true;
};





// 处理审批
const handleApprove = () => {
  approveFormRef.value.validate((errors) => {
    if (errors) {
      return;
    }

    // 如果是状态2且审批通过，检查交易编号
    if (
      basicInfo.value.tradeStatus === 2 &&
      approveForm.approvalResult === "approved"
    ) {
      // 验证交易编号
      if (approveForm.tradeCodeType === "manual" && !approveForm.tradeCode) {
        Message.warning("请输入交易编号");
        return;
      }
    }

    approveLoading.value = true;

    // 构建审批参数
    const approveData = {
      tradeApplicationId: props.tradeApplicationId,
      agree: approveForm.approvalResult === "approved" ? 1 : 2, // 1-同意，2-不同意
      refuseReason:
        approveForm.approvalResult !== "approved"
          ? approveForm.approvalComment
          : "",
      tradeCodeType: approveForm.tradeCodeType,
      tradeCode:
        approveForm.tradeCodeType === "manual" ? approveForm.tradeCode : null,
    };

    // 调用审批API
    approveTradeApplicationApi(approveData)
      .then(() => {
        Message.success("审批操作成功");
        approveModalVisible.value = false;

        // 重置审批表单
        resetApproveForm();

        // 重新加载页面数据
        loadBasicInfo();

        emit("approved", {
          tradeApplicationId: props.tradeApplicationId,
          ...approveForm,
        });
      })
      .catch((error) => {
        console.error("审批操作失败:", error);
        Message.error("审批操作失败，请重试");
      })
      .finally(() => {
        approveLoading.value = false;
      });
  });
};

// 切换信息展开状态
const toggleInfoExpand = () => {
  infoExpanded.value = !infoExpanded.value;
  activeKeys.value = infoExpanded.value ? ["basic"] : [];
};

// 获取状态颜色
const getStatusColor = (tradeStatus) => {
  if (!tradeStatus || !dicts[DICT.lindiTradeStatus]) {
    return "gray";
  }
  const dict = dicts[DICT.lindiTradeStatus].find(
    (d) => String(d.dictKey) === String(tradeStatus)
  );
  return dict?.dictClass || "gray";
};

// 获取状态文本
const getStatusText = (tradeStatus) => {
  if (!tradeStatus || !dicts[DICT.lindiTradeStatus]) {
    return "未知状态";
  }
  const dict = dicts[DICT.lindiTradeStatus].find(
    (d) => String(d.dictKey) === String(tradeStatus)
  );
  return dict?.dictValue || "未知状态";
};





// 重置审批表单
const resetApproveForm = () => {
  approveForm.approvalResult = "";
  approveForm.approvalComment = "";
  approveModalVisible.value = false;
};

// 加载基础信息
const loadBasicInfo = () => {
  if (!props.tradeApplicationId) {
    return;
  }
  loading.value = true;

  getTradeApplicationByTradeApplicationIdApi(props.tradeApplicationId)
    .then((res) => {
      // 设置基础信息
      basicInfo.value = {
        ...res,
        tradeStatus: res.tradeStatus || res.status || "submitted",
        createTime: res.createTime || "",
        submitter:
          res.submitter || res.enterpriseAccount?.enterprisePerson || "",
        enterpriseName:
          res.enterpriseAccount?.enterpriseName || res.enterpriseName || "",
      };

      // 处理附件数据
      const redlineFiles = [];
      const attachmentFiles = [];

      // 处理红线图文件
      if (res.redlineMapFile) {
        redlineFiles.push(res.redlineMapFile);
      }

      // 处理相关附件
      if (res.otherFilesVO && Array.isArray(res.otherFilesVO)) {
        attachmentFiles.push(...res.otherFilesVO);
      }

      attachmentData.value = {
        redlineFiles,
        attachmentFiles,
      };
    })
    .catch((error) => {
      console.error("获取交易申请详情失败:", error);
      Message.error("获取交易申请详情失败");
    })
    .finally(() => {
      loading.value = false;
    });
};

// 组件挂载时加载数据
onMounted(() => {
  loadBasicInfo();
});

// 监听tradeApplicationId变化
watch(
  () => props.tradeApplicationId,
  (newId) => {
    if (newId) {
      loadBasicInfo();
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.process-container {
  padding: 16px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.top-bar {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.process-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mb-4:last-child {
  margin-bottom: 0;
}

.approve-modal-content .contract-section {
  margin: 16px 0;
}

.approve-modal-content .approve-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e5e6eb;
}

/* 模板信息展示样式 */
.template-info-section {
  margin: 16px 0;
}

.template-info-card {
  background: #fafbfc;
  border: 1px solid #e5e6eb;
  border-radius: 6px;
}

.template-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.template-icon {
  flex-shrink: 0;
}

.template-basic-info {
  flex: 1;
  min-width: 0;
}

.template-name {
  font-weight: 500;
  font-size: 16px;
  color: #1d2129;
  margin-bottom: 4px;
}

.template-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.template-descriptions {
  margin: 16px 0;
}

.template-actions {
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #e5e6eb;
}

.bg-blue-100 {
  background-color: #e8f4ff;
}

.text-blue-600 {
  color: #165dff;
}

.bg-purple-100 {
  background-color: #f5e8ff;
}

.text-purple-600 {
  color: #722ed1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .process-container {
    padding: 12px;
  }

  .top-bar {
    padding: 12px;
  }

  .top-bar .arco-space {
    width: 100%;
    justify-content: stretch;
  }

  .top-bar .arco-btn {
    flex: 1;
  }
}
</style>
